package com.zzr.demo.redis.controller;

import com.zzr.demo.redis.model.Person;
import com.zzr.demo.redis.service.LockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author: xiaomi
 * @date: 2021/10/7
 * @description:
 */
@RestController()
@RequestMapping("distribute/lock")
@Api(tags = "分布式锁")
@Slf4j
public class LockController {

    @Autowired
    LockService lockService;

    /**
     * 多个请求时只能阻塞
     *
     * @param time
     * @return
     */
    @GetMapping("/lockAndExecute/{time}")
    @ApiOperation("获取分布式锁并执行")
    public boolean lockAndExecute(@PathVariable("time") Long time) {
        String lock = lockService.lock();
        if ("".equals(lock)) {
            //说明没有获得锁
            return false;
        }
        //已经获得锁，开始执行
        boolean res = true;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
            res = false;
        } finally {
            lockService.unlock();
            return res;
        }
    }
}
